package cn.fastdfs.util;

import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;

public class FastDFSUtils {
    private static   String key="123456";
    private static StorageClient1 client1=null;
    static {
        try {
            ClientGlobal.initByProperties("fastdfs-client.properties");
            TrackerClient trackerClient=new TrackerClient();
            TrackerServer trackerServer=trackerClient.getConnection();
            client1= new StorageClient1(trackerServer,null);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }
    public static String upload(MultipartFile file){
        String oldName=file.getOriginalFilename();
        try {
            System.out.println(oldName.substring(oldName.lastIndexOf(".")+1));
            System.out.println(client1);
            return client1.upload_file1(file.getBytes(),oldName.substring(oldName.lastIndexOf(".")+1),null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 因为配置了访问检测，所以写一个返回带密钥的方法
     * @param groupFile_url
     * @return
     * @throws MyException
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    public static String getHasTokenUrl(String groupFile_url) throws MyException, UnsupportedEncodingException, NoSuchAlgorithmException {
        String filename=groupFile_url.substring(groupFile_url.indexOf("/") + 1);
        String ip="http://192.168.1.8";
        String groupFilename="/group1/"+filename;
        int ts = (int) Instant.now().getEpochSecond();
        //根据文件名、时间、密钥生成token
        String token = ProtoCommon.getToken(filename, ts, key);
        StringBuilder sb = new StringBuilder();
        sb.append(ip).append(groupFilename).append("?token="+token).append("&ts="+ts);
        System.out.println(sb.toString());
        return sb.toString();
    }

}
